<template>
  <div class="questionselect-h5-container">
    <div class="questionselect-h5-title-row">
      <div class="questionselect-h5-title">
        第{{ index + 1 }}题（{{ question.type }}题）
      </div>
    </div>
    <div class="questionselect-h5-content-area">
      <!-- 仅拍照题目显示图片且支持点击放大，其他题型照旧 -->
      <template v-if="question.type === '拍照'">
        <div v-if="photoQuestionImgs.length" class="questionselect-h5-img photo-img-list">
          <template v-for="(img, idx) in photoQuestionImgs" :key="img">
            <img :src="img" alt="题目图片" class="photo-img-item" style="cursor:pointer"
              @click="handlePictureCardPreview({ url: img })" />
          </template>
        </div>
      </template>
      <template v-else>
        <div class="questionselect-h5-content" v-html="question.context"></div>
        <div v-if="question.img" class="questionselect-h5-img">
          <img :src="question.img" alt="题目图片" style="cursor:pointer"
            @click="handlePictureCardPreview({ url: question.img })" />
        </div>
      </template>
    </div>
    <!-- 图片预览弹窗（自定义H5全屏预览） -->
    <div v-if="dialogVisible" class="h5-img-preview" @click="dialogVisible = false">
      <img :src="dialogImageUrl" class="h5-img-preview-img" @click.stop />
      <div class="h5-img-preview-close" @click.stop="dialogVisible = false">×</div>
    </div>
    <div class="questionselect-h5-answer-area">
      <div class="questionselect-h5-answer-title">您的答案：</div>
      <template v-if="question.type === '判断'">
        <div class="questionselect-h5-judge-row">
          <div class="judge-btn" :class="{ active: data == true, disabled: isDisabled }"
            @click="!isDisabled && panduan(true)">正确</div>
          <div class="judge-btn" :class="{ active: data == false, disabled: isDisabled }"
            @click="!isDisabled && panduan(false)">错误</div>
        </div>
      </template>
      <template v-else-if="question.type === '单选'">
        <el-radio-group v-model="data" class="questionselect-h5-radio-group custom-radio-group" :disabled="isDisabled">
          <el-radio v-for="(v, k) in option" :key="k" :value="choice[k]" class="questionselect-h5-radio custom-radio"
            border :disabled="isDisabled">
            <span v-if="image(v)" class="choice-img-wrap">
              <img :src="v" class="choice-img" style="cursor:pointer"
                @click.stop="handlePictureCardPreview({ url: v })" />
            </span>
            <span v-else>{{ v }}</span>
          </el-radio>
        </el-radio-group>
      </template>
      <template v-else-if="question.type === '多选'">
        <el-checkbox-group v-model="data" class="questionselect-h5-checkbox-group custom-checkbox-group"
          :disabled="isDisabled">
          <el-checkbox v-for="(v, k) in option" :key="k" :value="choice[k]"
            class="questionselect-h5-checkbox custom-checkbox" border :disabled="isDisabled">
            <span v-if="image(v)" class="choice-img-wrap">
              <img :src="v" class="choice-img" style="cursor:pointer"
                @click.stop="handlePictureCardPreview({ url: v })" />
            </span>
            <span v-else>{{ v }}</span>
          </el-checkbox>
        </el-checkbox-group>
      </template>
      <template v-else-if="question.type === '填空'">
        <div class="questionselect-h5-input-wrap">
          <el-input v-model="data" type="textarea" :rows="3" placeholder="请输入答案" class="questionselect-h5-input"
            :disabled="isDisabled" />
        </div>
      </template>
      <template v-else-if="question.type === '拍照'">
        <el-upload class="questionselect-h5-upload" action="#" :http-request="handlePhotoUpload" :show-file-list="true"
          :file-list="photoFileList" list-type="picture-card" :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove" ref="photoUpload" :disabled="isDisabled" :limit="9" multiple>
          <el-button type="primary" class="questionselect-h5-upload-btn" :disabled="isDisabled">+ 拍照上传</el-button>
        </el-upload>
      </template>
    </div>
  </div>
</template>
<script setup lang="ts">
import {
  computed,
  defineProps,
  nextTick,
  onMounted,
  PropType,
  ref,
  toRefs,
  watch
} from "vue";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import questionhtml from "../../../util/htmlstring";
import { isImage } from "../../../util/RegExp";
import updateoss from "../../../util/updateoss";

const props = defineProps({
  index: {
    type: Number as PropType<number>,
    default: 1,
  },
  question: {
    type: Object as PropType<Studycodemodel.Imatchquestion>,
    required: true,
  },
  setuserdata: {
    type: Function,
    required: true,
  },
  userdata: {
    type: Object,
  },
  match: { type: Object as PropType<Studycodemodel.Iactivity> },
  submit: { type: Function },
  isMatch: { type: Boolean },
  h5: { type: Boolean, default: false },
  onlyAnswer: { type: Boolean, default: false },
  total: { type: Number, default: 1 },
  remainStr: { type: String, default: "" },
  toPrev: { type: Function },
  toNext: { type: Function },
  readonly: { type: Boolean, default: false }
});

const choice = ['A', 'B', 'C', 'D'];
const { question, userdata } = toRefs(props);

// 新增：拍照题内容图片
const photoQuestionImgs = computed(() => {
  // 支持 images 为数组或字符串
  if (question.value.type === '拍照' && question.value.images) {
    if (Array.isArray(question.value.images)) {
      return question.value.images;
    }
    if (typeof question.value.images === 'string') {
      // 兼容单个图片字符串
      return [question.value.images];
    }
  }
  return [];
});

const option = computed(() => {
  if (question.value.answer) {
    return question.value.answer.options || [];
  }
  return [];
});

const data = ref<boolean | string | string[]>();
const photoFileList = ref<any[]>([]);
const photoUpload = ref();
const dialogVisible = ref(false);
const dialogImageUrl = ref('');

// 新增：统一禁用判断
const isDisabled = computed(() => props.readonly);

function normalizeDataByType(val: any, type: string) {
  if (type === '多选') {
    // 多选必须是数组，字符串转为数组，null/undefined转空数组
    if (Array.isArray(val)) return val;
    if (typeof val === 'string' && val) return [val];
    if (val == null) return [];
    return [];
  }
  if (type === '单选') {
    // 单选必须是字符串，数组取第一个，null/undefined转空串
    if (typeof val === 'string') return val;
    if (Array.isArray(val) && val.length > 0) return val[0];
    if (val == null) return '';
    return '';
  }
  // 判断/填空/拍照等类型原样返回
  return val;
}

function start() {
  nextTick(() => {
    if (userdata?.value && question.value.ID) {
      const t = userdata.value[question.value.ID];
      if (question.value.type === "拍照") {
        if (t && Array.isArray(t) && t.length > 0) {
          photoFileList.value = t.map((url: string) => ({
            name: url.split('/').pop(),
            url
          }));
        } else {
          photoFileList.value = [];
        }
      } else {
        data.value = normalizeDataByType(t, question.value.type);
      }
    }
    questionhtml()
  });
}
onMounted(() => {
  start();
});

watch(
  () => question.value,
  () => {
    start();
  }
);

watch(
  () => data.value,
  () => {
    if (question.value.type !== "拍照") {
      // 存储时也做类型兼容
      if (question.value.type === '多选') {
        // 多选存数组
        props.setuserdata(question.value.ID, Array.isArray(data.value) ? data.value : (data.value ? [data.value] : []));
      } else if (question.value.type === '单选') {
        // 单选存字符串
        props.setuserdata(question.value.ID, typeof data.value === 'string' ? data.value : (Array.isArray(data.value) && data.value.length > 0 ? data.value[0] : ''));
      } else {
        props.setuserdata(question.value.ID, data.value);
      }
    }
  }
);

function image(str: string) {
  return isImage.test(str);
}

function panduan(t: boolean) {
  data.value = t;
}

function xuanze(t: string, type?: boolean) {
  if (type) {
    if (!Array.isArray(data.value)) {
      data.value = [];
    }
    const f = data.value.findIndex((v) => v === t);
    if (f !== -1) {
      data.value.splice(f, 1);
    } else {
      if (data.value.length >= 4) {
        data.value.splice(0, 1);
      }
      data.value.push(t);
    }
  } else {
    data.value = t;
  }
}

// 拍照题上传，支持多张
async function handlePhotoUpload(option: any) {
  const dataoss = await updateoss([option.file]);
  if (dataoss && dataoss.url) {
    // 修复：用新数组赋值，确保响应式
    photoFileList.value = [
      ...photoFileList.value,
      {
        name: dataoss.url.split('/').pop(),
        url: dataoss.url,
      }
    ];
    // 答案存数组，存所有图片url
    props.setuserdata(question.value.ID, photoFileList.value.map(f => f.url));
  }
  photoUpload.value?.clearFiles();
}

function handlePictureCardPreview(file: any) {
  // 兼容字符串和对象
  dialogImageUrl.value = typeof file === 'string' ? file : file.url;
  dialogVisible.value = true;
}
function handleRemove(file: any, fileList: any) {
  photoFileList.value = fileList;
  props.setuserdata(question.value.ID, fileList.map((f: any) => f.url));
}

</script>
<style scoped>
.questionselect-h5-container {
  background: #fff;
  border-radius: 12px;
  margin: 0;
  padding: 0;
  box-shadow: none;
  display: flex;
  flex-direction: column;
  min-height: 480px;
}

.questionselect-h5-title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 16px 0 16px;
}

.questionselect-h5-title {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

.questionselect-h5-content-area {
  padding: 0 10px;
  margin-top: 10px;
}

.questionselect-h5-content {
  font-size: 15px;
  color: #333;
  margin-bottom: 12px;
  word-break: break-all;
  background: #f5f6fa;
  border-radius: 8px;
  padding: 12px;
}

.questionselect-h5-img {
  text-align: center;
  margin-bottom: 10px;
}

.questionselect-h5-img img {
  max-width: 100%;
  border-radius: 4px;
}

.questionselect-h5-audio {
  margin-bottom: 10px;
}

.questionselect-h5-answer-area {
  margin: 0 16px 12px 16px;
  padding: 12px 0 0 0;
  border-top: 1px solid #f0f0f0;
}

.questionselect-h5-answer-title {
  font-weight: bold;
  margin-bottom: 12px;
  font-size: 16px;
  text-align: left;
}

.questionselect-h5-judge-row {
  display: flex;
  justify-content: flex-start;
  gap: 24px;
  margin-bottom: 8px;
}

.judge-btn {
  width: 100px;
  height: 44px;
  line-height: 44px;
  border-radius: 22px;
  background: #f5f6fa;
  color: #409eff;
  font-size: 16px;
  text-align: center;
  cursor: pointer;
  border: 1px solid #409eff;
  transition: all 0.2s;
}

.judge-btn.active {
  background: #409eff;
  color: #fff;
}

/* 单选优化 */
.custom-radio-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: flex-start;
  margin-bottom: 8px;
}

.custom-radio {
  margin: 0;
  min-width: 0;
  border-radius: 8px !important;
  border: 1px solid #e0e0e0 !important;
  background: #f8fafd !important;
  font-size: 15px;
  height: 56px;
  line-height: 56px;
  display: flex;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
  overflow: hidden;
}

.custom-radio .el-radio__input {
  margin-right: 12px;
}

.custom-radio .el-radio__label {
  font-size: 15px;
  color: #222;
  width: 100%;
  display: flex;
  align-items: center;
}

/* 复选优化 */
.custom-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: flex-start;
  margin-bottom: 8px;
}

.custom-checkbox {
  margin: 0;
  min-width: 0;
  border-radius: 8px !important;
  border: 1px solid #e0e0e0 !important;
  background: #f8fafd !important;
  font-size: 15px;
  height: 56px;
  line-height: 56px;
  display: flex;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
  overflow: hidden;
}

.custom-checkbox .el-checkbox__input {
  margin-right: 12px;
}

.custom-checkbox .el-checkbox__label {
  font-size: 15px;
  color: #222;
  width: 100%;
  display: flex;
  align-items: center;
}

/* 选项图片包裹，防止溢出 */
.choice-img-wrap {
  display: flex;
  align-items: center;
  max-width: 120px;
  max-height: 40px;
  overflow: hidden;
}

.choice-img {
  max-height: 40px;
  max-width: 100%;
  border-radius: 4px;
  margin-left: 8px;
  object-fit: contain;
  display: block;
}

/* 填空优化 */
.questionselect-h5-input-wrap {
  width: 100%;
  display: flex;
  align-items: flex-start;
  margin-bottom: 8px;
}

.questionselect-h5-input {
  width: 100%;
  background: #f8fafd;
  border-radius: 8px;
  font-size: 15px;
  min-height: 44px;
  border: 1px solid #e0e0e0;
  box-sizing: border-box;
}

.questionselect-h5-upload {
  margin-bottom: 12px;
}

.questionselect-h5-upload-btn {
  width: 100%;
  height: 100%;
  /* background: #409eff; */
  color: #fff;
  border-radius: 6px;
}

.questionselect-h5-footer {
  display: flex;
  justify-content: space-between;
  margin: 12px 0 0 0;
  gap: 12px;
}

.questionselect-h5-btn {
  flex: 1;
  height: 42px;
  font-size: 16px;
  border-radius: 21px;
  background: #409eff;
  color: #fff;
  border: none;
}

.questionselect-h5-btn:disabled {
  background: #e0e0e0;
  color: #aaa;
}

.questionselect-h5-progress {
  text-align: center;
  color: #888;
  font-size: 14px;
  margin: 12px 0 0 0;
}

.danger {
  color: #e74c3c;
}
</style>

<style>
.questionselect-h5-container .el-dialog,
.questionselect-h5-container .el-dialog__body {
  padding: 4px;
}
</style>

<style scoped>
.h5-img-preview {
  position: fixed;
  z-index: 9999;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  animation: fadeIn .2s;
}

.h5-img-preview-img {
  max-width: 99%;
  /* max-height: 88vh; */
  background: #fff;
  object-fit: contain;
  box-shadow: 0 2px 16px rgba(0, 0, 0, 0.25);
}

.h5-img-preview-close {
  position: absolute;
  top: 18px;
  right: 18px;
  font-size: 32px;
  color: #fff;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  cursor: pointer;
  z-index: 10001;
  user-select: none;
  line-height: 1;
  /* 移除原有 line-height: 40px; */
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}
</style>

<style scoped>
.judge-btn.disabled {
  opacity: 0.5;
  pointer-events: none;
}
</style>